import { InnerMsg } from "../ClientServer";
import { MsgParser } from "./MsgParser";

export type onInnerMgsCallback = (cmd: number, data: InnerMsg) => void

export class Bridge {
    static id = 0;

    private _ws: WebSocket | null = null;
    private _ip: string = "";
    private _port: number = 0;
    private _msgParse: MsgParser | null = null
    private _onopen: Function | null = null;
    private _onmsg: onInnerMgsCallback | null = null;
    constructor(ip: string, port: number, onopen: Function, onmsg: onInnerMgsCallback) {
        Bridge.id++;
        this._ip = ip;
        this._port = port;
        this._msgParse = new MsgParser();
        this._onopen = onopen;
        this._onmsg = onmsg;
        this.connect()
    }
    /**
     * 连接服务器
     */
    private connect() {
        let url = "ws://" + this._ip + ":" + this._port;
        this._ws = new WebSocket(url);
        this._ws.binaryType = 'arraybuffer'
        this._ws.onopen = (event: Event) => {
            console.log(`Bridge id:${Bridge.id},ip:${this._ip},port:${this._port}---onopen`)
            this._onopen!()
        };
        //接收消息
        this._ws.onmessage = (event: MessageEvent) => {
            const msg = event.data as ArrayBuffer;
            this._msgParse!.parse(msg, (cmd: number, unit8Array: Uint8Array) => {
                const data: InnerMsg = JSON.parse(Buffer.from(unit8Array).toString('utf-8'))
                if (this._onmsg) {
                    this._onmsg(cmd, data)
                }
            })
        };
        //错误提示
        this._ws.onerror = (event: Event) => {
            console.log(`Bridge id:${Bridge.id},ip:${this._ip},port:${this._port}---onerror`)
        };
        //关闭网络
        this._ws.onclose = (event: CloseEvent) => {
            console.log(`Bridge id:${Bridge.id},ip:${this._ip},port:${this._port}---onclose`)
        };
    }

    /*
     * 发送数据
     */
    sendData(cmd: number, data: InnerMsg) {
        const unit8Array: Uint8Array = Buffer.from(JSON.stringify(data), 'utf-8')
        this._ws!.send(this._msgParse!.wrap(cmd, unit8Array)!);
    }

}